package weaver.formmode.webservices;

import com.api.cube.util.CubeCipherUitl;
import com.api.formmode.cache.ModeFormFieldEncryptComInfo;
import com.engine.common.biz.EncryptConfigBiz;
import com.engine.cube.biz.CodeBuilder;
import com.engine.cube.cmd.card.CubeCheckCardRight;
import com.engine.cube.cmd.restfulinterface.DeleteModeDataByPK;
import com.engine.cube.util.AddSeclevelUtil;
import com.engine.cube.util.SaveConditionUtil;
import com.weaver.formmodel.util.DateHelper;
import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import weaver.conn.RecordSet;
import weaver.formmode.dao.FormInfoDao;
import weaver.formmode.data.ModeDataIDUpdateSingle;
import weaver.formmode.data.ModeDataIdUpdate;
import weaver.formmode.data.ModeDataInterface;
import weaver.formmode.log.FormmodeLog;
import weaver.formmode.setup.ModeRightInfo;
import weaver.formmode.setup.ModeSetUtil;
import weaver.formmode.view.ModeShareManager;
import weaver.formmode.view.ModeViewLog;
import weaver.formmode.virtualform.UUIDPKVFormDataSave;
import weaver.formmode.virtualform.VirtualFormHandler;
import weaver.formmode.webservices.exception.ModeDataExceptionEnum;
import weaver.formmode.webservices.exception.ModeDataServiceException;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.security.util.SecurityMethodUtil;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.form.FormManager;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class ModeDataServiceImpl extends FormmodeLog implements ModeDateService{

	private final static String base64Flag = "Base64_";
	private FieldInfo fieldInfo = new FieldInfo();
	private FileUtil fileutil = new FileUtil();
	private String oaip = getPropValue("OAIpaddress","Ipaddress");
	private String deljsonString = "";

	public String deleteModeDataById2(int modeId, int Id, int userId,String right,String doPageexpandInterface) {
		String returnxml = "";
		boolean flag = false;
		try {
			RecordSet rs = new RecordSet();
			FieldInfo fieldinfo = new FieldInfo();
			fieldinfo.getMainTableName(modeId);
			fieldinfo.getDetailTableNameList(modeId);

			String tablename = fieldinfo.getTablename();
			int formId = getFormIdByModeId(modeId);

			//校验权限
			if("Y".equalsIgnoreCase(right)) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("billid", Id);
				paramMap.put("type", 3);
				paramMap.put("modeId", modeId);
				paramMap.put("formId", formId);
				User user = new User(userId);
				CubeCheckCardRight cubeCheckCardRight = new CubeCheckCardRight(paramMap, user);
				Map<String, Object> rightInfo = cubeCheckCardRight.execute(null);
				String hasRight = Util.null2String(rightInfo.get("hasDeleteRight"));
				if (hasRight.contentEquals("false")) {
					returnxml = getReturnElements(Id, -1, "权限校验失败，无权限删除该数据");
					return returnxml;
				}
			}
			//权限校验结束

			boolean isVirtualForm = VirtualFormHandler.isVirtualForm(formId);
			String pkfieldname = "id";
			String dataSource = "";
			if(isVirtualForm){
				FormInfoDao formInfoDao = new FormInfoDao();
				Map<String, Object> formInfo = formInfoDao.getFormInfoById(formId);
				tablename = VirtualFormHandler.getRealFromName(tablename);
				pkfieldname = Util.null2String(formInfo.get("vprimarykey"));
				dataSource = getVDataSource(formInfo);
			}


			List detailtable_list = fieldinfo.getDetailtable_list();
			DeleteModeDataByPK deleteModeDataByPK = new DeleteModeDataByPK("",null,null);
			deleteModeDataByPK.createDelData(modeId+"");
			deljsonString = deleteModeDataByPK.getDeleteJson(formId+"",tablename,Id+"");

			//删除执行页面扩展
			if("Y".equalsIgnoreCase(doPageexpandInterface)){
				rs.executeQuery("select id from mode_pageexpand where issystem=1 and issystemflag=5 and modeid=" + modeId);
				if (rs.next()) {
					int pageexpandid = rs.getInt("id");
					doInterface(Id+"", formId+"", modeId+"", userId, pageexpandid, new HashMap<>());
				}
			}
			String detailtablename = "";
			String sql = "delete from "+tablename+" where "+pkfieldname+"=?";
			if(isVirtualForm){
				RecordSet rs2 = new RecordSet();
				rs2.executeQueryWithDatasource("select * from "+tablename+" where "+pkfieldname+"=?",dataSource,Id);
				Map<String,String> oldData = recordSet2Map(rs2);//将删除的数据打印到日志
				writeLog("deleteModeDataById.oldData:"+oldData);
				flag = rs.executeUpdateWithDatasource(sql,dataSource,Id);
			}else {
				flag = rs.executeUpdate(sql,Id);
			}
			for (int i = 0; i < detailtable_list.size(); i++) {
				detailtablename = detailtable_list.get(i).toString();
				sql = "delete from "+detailtablename+" where mainid=?";
				rs.executeUpdate(sql,Id);
			}
			//保存其他操作
			saveModeDataOthers(modeId, Id, userId, "deleteAll", "5");
			if(flag){
				returnxml = getReturnElements(Id, 0, SystemEnv.getHtmlLabelName(83885,weaver.general.Util.threadVarLanguage()));//操作成功！
			}else{
				returnxml = getReturnElements(Id, -1, SystemEnv.getHtmlLabelName(83912,weaver.general.Util.threadVarLanguage()));//操作失败！
			}
		} catch (Exception e) {
			e.printStackTrace();
			writeLog("deleteModeDataById:"+e);
			returnxml = getErrorMsg(e.getMessage());
		}
		return returnxml;
	}

	public String deleteModeDataById(int modeId, int Id, int userId,String right) {
		return deleteModeDataById2(modeId,Id,userId,right,"Y");
	}

	public String saveModeData(String paramXml) {
		//writeLog("saveModeData paramXml:"+paramXml);
		String returnxml="";
		boolean flag = false;
		String errorMsg = "";
		Integer id = -1;
		boolean isBase64String = false;
		try {
			if(Util.null2String(paramXml).length()>0&&paramXml.startsWith(base64Flag)){
				paramXml = paramXml.replace(base64Flag, "");
				paramXml = new String(weaver.general.Base64.decode(paramXml.getBytes()));
				isBase64String = true;
			}
			RecordSet rs = new RecordSet();

			//创建一个SAXBuilder对象
			SAXBuilder saxBuilder = new SAXBuilder();

            Document doc = null;
            try {
                SecurityMethodUtil.setSaxBuilderFeature(saxBuilder);
                doc = saxBuilder.build(new ByteArrayInputStream(paramXml.getBytes("UTF-8")));
            } catch (Exception e){
                writeLog(e);
                throw new ModeDataServiceException(ModeDataExceptionEnum.PARSE_XML_FAILURE.toStringWithExp(e.getMessage()));
            }

			//Document doc = saxBuilder.build(new File("E:\\cc.xml"));
			Element root = doc.getRootElement();

			Element headerElement = root.getChild("header");
			if(headerElement == null){
			    throw new ModeDataServiceException(ModeDataExceptionEnum.HEADER_NODE_NOT_FOUND.toString());
            }
            Integer userid = Util.getIntValue(headerElement.getChildText("userid"));
			Integer modeid = Util.getIntValue(headerElement.getChildText("modeid"));
			boolean isDoInterface = false;
			String doPageexpandInterface = Util.null2String(headerElement.getChildText("doPageexpandInterface"));
			if(doPageexpandInterface.equalsIgnoreCase("Y")){
				isDoInterface = true;
			}
			id = Util.getIntValue(headerElement.getChildText("id"),-1);

			if(modeid == -1){
                throw new ModeDataServiceException(ModeDataExceptionEnum.MODEID_NOT_FOUND.toString());
            }
			if(userid == -1){
                throw new ModeDataServiceException(ModeDataExceptionEnum.USERID_NOT_FOUND.toString());
            }

            Element searchElement = root.getChild("search");
            if(searchElement == null){
                throw new ModeDataServiceException(ModeDataExceptionEnum.SEARCH_NODE_NOT_FOUND.toString());
            }
			//根据modeid 获得 formid
			//select formid from modeinfo where id=1
            Integer formid = -1;
            String tablename = "";

			String sql = "select w.tablename,w.id from modeinfo m,workflow_bill w where w.id=m.formid and m.id=?";
			rs.executeQuery(sql,modeid);
			if(rs.next()) {
                formid = Util.getIntValue(rs.getString("id"));
                tablename = Util.null2String(rs.getString("tablename"));
            }

            if(formid == -1){
                throw new ModeDataServiceException(ModeDataExceptionEnum.FORMID_NOT_FOUND.toString());
            }
			boolean isVirtualForm = VirtualFormHandler.isVirtualForm(formid);
			String dataSource = "";
			String pkfieldname = "id";
			if(isVirtualForm){
				FormInfoDao formInfoDao = new FormInfoDao();
				Map<String, Object> formInfo = formInfoDao.getFormInfoById(formid);
				dataSource = getVDataSource(formInfo);
				pkfieldname = Util.null2String(formInfo.get("vprimarykey"));
				tablename = VirtualFormHandler.getRealFromName(tablename);
			}
            if(tablename.length()>33&&tablename.charAt(32)=='_'){
                throw new ModeDataServiceException(ModeDataExceptionEnum.NOT_SUPPORT_VIRFORM.toString());
            }

			String fields = "";
			String fieldsValue = "";
			String fieldtype = "";
			String updateFields = "";

			//解析主表单xml数据
			String filedname = "";
			String filedlabel = "";
			String filedvalue = "";
			Element maintableElement = root.getChild("data");
            if(maintableElement == null){
                throw new ModeDataServiceException(ModeDataExceptionEnum.DATA_NODE_NOT_FOUND.toString());
            }

            maintableElement = maintableElement.getChild("maintable");
            if(maintableElement == null){
                throw new ModeDataServiceException(ModeDataExceptionEnum.MAINTABLE_NODE_NOT_FOUND.toString());
            }

			List<Element> mainField_list = maintableElement.getChildren("field");
			//长字段值不能直接拼接sql，包括html文本、多选
			List<Object> clobValueList = new ArrayList<Object>();
			List<Object> clobValueList_update = new ArrayList<Object>();
			List<Object> clobFieldList_update = new ArrayList<Object>();
			for (int i = 0; i < mainField_list.size(); i++) {
				filedname = Util.null2String(mainField_list.get(i).getChildText("filedname"));
				filedlabel = Util.null2String(mainField_list.get(i).getChildText("filedlabel"));
				filedvalue = Util.null2String(mainField_list.get(i).getChildText("filedvalue"));
				filedvalue = Util.toHtmlForWorkflow(filedvalue);
				fieldtype = Util.null2String(mainField_list.get(i).getChildText("fileddbtype")).toLowerCase();

				fields+=filedname;
				fields+=",";

				//判断加密
				filedvalue = isFirldNeedEncrypt(filedvalue,tablename,formid,filedname);
				//insert sqlfield
				//fieldsValue+="'"+filedvalue+"'";
				if(fieldtype.startsWith("int") || fieldtype.startsWith("float") || fieldtype.startsWith("number") || fieldtype.startsWith("decimal")){
					fieldsValue+=(!filedvalue.equals("")?filedvalue:"null")+"";
				}else if(fieldtype.equals("clob") || fieldtype.equals("text")){
					clobValueList.add(filedvalue);
					fieldsValue+="?";
				}else{
					fieldsValue+="'"+filedvalue+"'";
				}
				fieldsValue+=",";

				//update sqlfield
				if(!"".equals(updateFields) && !updateFields.endsWith(","))updateFields+=",";
				if(fieldtype.startsWith("int") || fieldtype.startsWith("float") || fieldtype.startsWith("number") || fieldtype.startsWith("decimal")){
					updateFields+=filedname+"="+(!filedvalue.equals("")?filedvalue:"null")+"";
				}else if(fieldtype.equals("clob") || fieldtype.equals("text")){
					clobFieldList_update.add(filedname);
					clobValueList_update.add(filedvalue);
					//updateFields+="?";
				}else{
					updateFields+=filedname+"='"+filedvalue+"'";
				}
			}
			if(!"".equals(updateFields) && updateFields.endsWith(",")) {
				//避免最后一位是clob类型字段，多拼逗号，影响后边逻辑
				updateFields = updateFields.substring(0,updateFields.length()-1);
			}
			Object[] clobObjects = new Object[clobValueList.size()];
			for (int i=0;i<clobValueList.size();i++) {
				clobObjects[i] = clobValueList.get(i);
			}
			//添加uuid列
			ModeDataIDUpdateSingle.INSTANCE.addModeUUIDColumnForTable(tablename);//根据表名添加modeuuid
			UUIDPKVFormDataSave uuidPKVFormDataSave = new UUIDPKVFormDataSave();
			String uuid = (String)uuidPKVFormDataSave.generateID(null);//获取uuid
			boolean isAdd=false;
			if(id == null || id == -1){
				isAdd=true;
				if(isVirtualForm){
					fields = removePrefixAndSuffix(fields,",");
					fields = fields+",modeuuid";//置顶列
					fieldsValue = removePrefixAndSuffix(fieldsValue,",");
					fieldsValue = fieldsValue+",'"+uuid+"'";
					sql = "insert into "+tablename+" ("+fields+") values ("+fieldsValue+")";
					writeLog(sql);
					flag = rs.executeUpdateWithDatasource(sql,dataSource,clobObjects);
					//rs.executeUpdateWithDatasource(s, poolname, params)
					//添加置顶逻辑
					if(flag){
						SaveConditionUtil.buildTopDataWebServiceInsert(uuid,tablename,formid,modeid);
					}
				}else{
					sql = "insert into "+tablename+" ("+fields+"formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,modeuuid) values ("+fieldsValue+" "+modeid+","+userid+",0,'"+getCurrentDate()+"','"+getCurrentTime()+"','"+uuid+"')";
					flag = rs.executeUpdate(sql,clobObjects);
					//添加置顶逻辑
					if(flag){
						SaveConditionUtil.buildTopDataWebServiceInsert(uuid,tablename,formid,modeid);
						//添加密级 逻辑更新为 公开级别
						Map<String,Object> params = new HashMap<>();
						params.put("billid",uuid);
						params.put("billtablename",tablename);
						params.put("formmodeid",modeid);
						AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
						addSeclevelUtil.updateSeclevelForWebServiceInsert(params);
					}
					writeLog(sql);
				}
				if(!flag){
                    throw new ModeDataServiceException(ModeDataExceptionEnum.INSERT_SQL_FAILURE.toStringWithExp(sql));
					//return getReturnElements(null, -1, "操作失败！");
				}
				sql = "select max(id) as id from "+tablename+" where modeuuid=?";
				rs.executeQuery(sql,uuid);
				id = rs.next()?Util.getIntValue(rs.getString("id")):0;
				CodeBuilder cbuild = new CodeBuilder(modeid);
				cbuild.getModeCodeStr(formid,id);
				//如果有草稿状态，那么webservice数据直接设置为0正式的
				ModeSetUtil modeSetUtil = new ModeSetUtil();
				modeSetUtil.setModedatastatusValue(rs,modeid,id,tablename,0);

				//新建保存
				/*if(isDoInterface){
					rs.executeQuery("select id from mode_pageexpand where issystem=1 and issystemflag=1 and modeid=" + modeid);
					if (rs.next()) {
						int pageexpandid = rs.getInt("id");
						doInterface(id+"", formid+"", modeid+"", userid, pageexpandid, new HashMap<>());
					}
				}*/
			}else{
				if(!"".equals(updateFields)){
					isAdd=false;
					Object[] clobObjects_update = new Object[clobValueList_update.size()+1];
					//clobObjects_update[0] = id;
					for (int i=0;i<clobValueList_update.size();i++) {
						clobObjects_update[i] = clobValueList_update.get(i);
					}
					clobObjects_update[clobValueList_update.size()] = id;
					if (!clobFieldList_update.isEmpty()) {
						for (int i=0;i<clobFieldList_update.size();i++) {
							updateFields += ","+clobFieldList_update.get(i) + "= ? ";
						}
					}
					if(isVirtualForm){
						RecordSet rs2 = new RecordSet();
						sql = "select * from "+tablename+" where "+pkfieldname+"=?";
						rs2.executeQueryWithDatasource(sql,dataSource,id);
						Map<String,String> oldData = recordSet2Map(rs2);//将虚拟表单更新前将历史数据打印到日志
						writeLog("saveModeData.oldData:"+oldData);
						sql = "update "+tablename+" set "+updateFields+" where "+pkfieldname+"=?";
						flag = rs.executeUpdateWithDatasource(sql,dataSource,clobObjects_update);
						if(flag){
							//添加置顶计算
							SaveConditionUtil.buildTopDataWebServiceUpdate(id,tablename,formid,pkfieldname,modeid);
							//添加密级 逻辑更新为 公开级别
							Map<String,Object> params = new HashMap<>();
							params.put("billid",id+"");
							params.put("billtablename",tablename);
							params.put("formmodeid",modeid);
							AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
							addSeclevelUtil.updateSeclevelForWebServiceUpdate(params);
						}
					}else {
						//updateFields+=",modedatamodifier="+userid+",modedatamodifydatetime='"+ TimeUtil.getCurrentTimeString()+"'";
						sql = "update "+tablename+" set "+updateFields+" where id=?";
						flag = rs.executeUpdate(sql,clobObjects_update);
						if(flag){
							//添加置顶计算
							SaveConditionUtil.buildTopDataWebServiceUpdate(id,tablename,formid,null,modeid);
							//添加密级 逻辑更新为 公开级别
							Map<String,Object> params = new HashMap<>();
							params.put("billid",id+"");
							params.put("billtablename",tablename);
							params.put("formmodeid",modeid);
							AddSeclevelUtil addSeclevelUtil = new AddSeclevelUtil();
							addSeclevelUtil.updateSeclevelForWebServiceUpdate(params);
						}
					}
					if(flag){
						//更新最后修改人和修改时间
			        	ModeDataIdUpdate modeDataIdUpdate = new ModeDataIdUpdate();
			        	RecordSet rSet = new RecordSet();
			        	if(!VirtualFormHandler.isVirtualForm(formid)){	//如果是虚拟表单，则不需要创建这些字段。
			        		String modifydatatime = DateHelper.getCurrentDate()+" "+DateHelper.getCurrentTime();
			        		modeDataIdUpdate.updateModifyInfo(tablename);
			        		if(id>0){
			        			//更新最后修改人和最后修改时间
			        			String modifysql = "update "+tablename+" set modedatamodifier=?,modedatamodifydatetime=? where id=?";
			        			rSet.executeUpdate(modifysql, userid,modifydatatime,id);
			        		}
			        	}
					}
					//System.out.println(sql);
					writeLog(sql);
					if(!flag){
                        throw new ModeDataServiceException(ModeDataExceptionEnum.UPDATE_SQL_FAILURE.toStringWithExp(sql));
						//return getReturnElements(null, -1, "操作失败！");
					}
					//编辑保存
					/*if(isDoInterface){
						rs.executeQuery("select id from mode_pageexpand where issystem=1 and issystemflag=2 and modeid=" + modeid);
						if (rs.next()) {
							int pageexpandid = rs.getInt("id");
							doInterface(id+"", formid+"", modeid+"", userid, pageexpandid, new HashMap<>());
						}
					}*/
				}
			}

			//保存其他操作 - 权限 + 日志
			saveModeDataOthers(modeid, id, userid, "save", "6");

			//解析files标签
			resolveFilesElement(modeid, userid, id, tablename, maintableElement.getChildren("files"));

			//解析明细表单xml数据
			int detailtableid = -1;
			String rowid = "";
			String action = "";
			String dtfiledname = "";
			String dtfiledlabel = "";
			String dtfiledvalue = "";
			String detailtablename = "";
			FormManager fManager = new FormManager();
			if(root.getChild("data").getChild("detail")!=null&&root.getChild("data").getChild("detail").getChildren("detailtable")!=null){
			List<Element> detailtable_list = root.getChild("data").getChild("detail").getChildren("detailtable");
			//长字段值不能直接拼接sql，包括html文本、多选
			List<Object> clobValueList_detail = new ArrayList<Object>();
			List<Object> clobValueList_detail_update = new ArrayList<Object>();
			List<Object> clobFieleList_detail_update = new ArrayList<Object>();
			for (int i = 0; i < detailtable_list.size(); i++) {  //循环明细表
				detailtableid = Util.getIntValue(detailtable_list.get(i).getAttributeValue("id"))+1;
				detailtablename=fManager.getDetailTablename(formid, detailtableid);
				List<Element> row_list = detailtable_list.get(i).getChildren("row");
				for (int k = 0; k < row_list.size(); k++) {  //循环各明细表行数据
					Element rowElements = row_list.get(k);

					rowid = rowElements.getAttributeValue("id");
					action = rowElements.getAttributeValue("action");

					fields = "";
					fieldsValue = "";
					fieldtype = "";
					updateFields = "";

					List<Element> detailField_list = rowElements.getChildren("field");
					for (int j = 0; j < detailField_list.size(); j++) { //循环明细表行字段数据
						dtfiledname = Util.null2String(detailField_list.get(j).getChildText("filedname"));
						dtfiledlabel = Util.null2String(detailField_list.get(j).getChildText("filedlabel"));
						dtfiledvalue = Util.null2String(detailField_list.get(j).getChildText("filedvalue"));
						dtfiledvalue = Util.toHtmlForWorkflow(dtfiledvalue);
						fieldtype = Util.null2String(detailField_list.get(j).getChildText("fileddbtype")).toLowerCase();
						//System.out.println(dtfiledname+"**"+dtfiledlabel+"**"+dtfiledvalue+"**"+action);

						//判断加密
						dtfiledvalue = isFirldNeedEncrypt(dtfiledvalue,detailtablename,detailtableid,dtfiledname);
						if(!"".equals(fields))fields+=",";
						fields+=dtfiledname;

						if(!"".equals(fieldsValue))fieldsValue+=",";
						if(fieldtype.startsWith("int") || fieldtype.startsWith("float") || fieldtype.startsWith("number") || fieldtype.startsWith("decimal")){
							fieldsValue+=(!dtfiledvalue.equals("")?dtfiledvalue:"null");
						}else if(fieldtype.equals("clob") || fieldtype.equals("text")){
							clobValueList_detail.add(filedvalue);
							fieldsValue+="?";
						}else{
							fieldsValue+="'"+dtfiledvalue+"'";
						}

						if(!"".equals(updateFields) && !updateFields.endsWith(","))updateFields+=",";
						if(fieldtype.startsWith("int") || fieldtype.startsWith("float") || fieldtype.startsWith("number") || fieldtype.startsWith("decimal")){
							updateFields+=dtfiledname+"="+(!dtfiledvalue.equals("")?dtfiledvalue:"null")+"";
						}else if(fieldtype.equals("clob") || fieldtype.equals("text")){
							clobFieleList_detail_update.add(dtfiledname);
							clobValueList_detail_update.add(filedvalue);
							//updateFields+=dtfiledname+"=？";;
						}else{
							updateFields+=dtfiledname+"='"+dtfiledvalue+"'";
						}
					}
					if(!"".equals(updateFields) && updateFields.endsWith(",")) {
						//避免最后一位是clob类型字段，多拼逗号，影响后边逻辑
						updateFields = updateFields.substring(0,updateFields.length()-1);
					}
					boolean isok = false;
					if("add".equalsIgnoreCase(action)){
						Object[] clobObjects_detail = new Object[clobValueList_detail.size()];
						for (int j=0;j<clobValueList_detail.size();j++) {
							clobObjects_detail[j] = clobValueList_detail.get(j);
						}
						sql = "insert into "+detailtablename+" (mainid,"+fields+") values ("+id+","+fieldsValue+")";
						if(fields.equals("")){
							sql = "insert into "+detailtablename+" (mainid) values ("+id+")";
						}
						isok = rs.executeUpdate(sql,clobObjects_detail);
					}else if("update".equalsIgnoreCase(action)){
						Object[] clobObjects_detail_update = new Object[clobValueList_detail_update.size()];
						for (int j=0;j<clobValueList_detail_update.size();j++) {
							clobObjects_detail_update[j] = clobValueList_detail_update.get(j);
						}
						if (!clobFieleList_detail_update.isEmpty()) {
							for (int c=0;c<clobFieleList_detail_update.size();c++) {
								updateFields += ","+clobFieleList_detail_update.get(c) + "= ? ";
							}
						}
						if(updateFields.trim().startsWith(",")){
							updateFields = updateFields.trim().substring(1);
						}
						if(updateFields.length()>0){
							sql = "update "+detailtablename+" set "+updateFields+" where id="+rowid;
							isok = rs.executeUpdate(sql,clobObjects_detail_update);
						}else{
							sql = "";
							this.writeLog("没有要更新的字段");
							isok = true;
						}
					}else if("delete".equalsIgnoreCase(action)){
						sql = "delete from "+detailtablename+" where id= "+rowid;
						isok = rs.executeUpdate(sql);
					}
					//boolean isok = rs.executeSql(sql,clobObjects_detail);
					writeLog(sql);
					if(!isok){
						throw new ModeDataServiceException(ModeDataExceptionEnum.DETAILTABLE_OPERATE_FAILURE.toStringWithExp(sql));
					}

					if("add".equalsIgnoreCase(action)){
						sql = "select max(id) as id from "+detailtablename+" where mainid=?";
						rs.executeQuery(sql,id);
						rs.next();
						rowid = Util.null2String(rs.getString("id"));
					}

					//解析files标签
					resolveFilesElement(modeid, userid, Integer.parseInt(rowid), detailtablename, rowElements.getChildren("files"));
				}
			}
		}
			//新建保存
			if(isDoInterface){//主表和明细表都处理完之后 触发接口动作
				String issystemflag=isAdd?"1":"2";// 新建保存 1  编辑保存 2
				rs.executeQuery("select id from mode_pageexpand where issystem=1 and issystemflag="+issystemflag+" and modeid=" + modeid);
				if (rs.next()) {
					int pageexpandid = rs.getInt("id");
					doInterface(id+"", formid+"", modeid+"", userid, pageexpandid, new HashMap<>());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			writeLog("saveModeData:"+e);
			errorMsg = e.getMessage();
		}
		if("".equals(errorMsg)) {
			returnxml = getReturnElements(id, 0, SystemEnv.getHtmlLabelName(83885, weaver.general.Util.threadVarLanguage()));//操作成功！
		} else {
			returnxml = getReturnElements(id, -1, errorMsg);
		}
		if(isBase64String){
			returnxml = new String(weaver.general.Base64.encode(returnxml.getBytes()));
		}
		//writeLog(returnxml);
		return returnxml;
	}

	public int getAllModeDataCount(int modeId, int userId, String conditions,String right) {
		RecordSet rs = new RecordSet();
		FieldInfo fieldinfo = new FieldInfo();
		fieldinfo.getMainTableName(modeId);
		String from = fieldinfo.getTablename();

		int formId = getFormIdByModeId(modeId);
		boolean isVirtualForm = VirtualFormHandler.isVirtualForm(formId);
		if (isVirtualForm){
			from = VirtualFormHandler.getRealFromName(from);
		}
		from += " ";
		String where = " where 1=1 ";
		if("y".equalsIgnoreCase(right.trim()) && !isVirtualForm){
			from +="t1,"+getShareSql(modeId, userId)+" t2 ";
			where += " and t1.id = t2.sourceid ";
		}

		if(!"".equals(conditions.trim())){
			conditions = " and "+conditions;
		}
		where += conditions;

		String sql = "select id from "+from+where;
		writeLog(sql);
		FormInfoDao formInfoDao = new FormInfoDao();
		Map<String, Object> formInfo = formInfoDao.getFormInfoById(formId);
		String dataSource = null;
		try {
			dataSource = this.getVDataSource(formInfo);
		} catch (ModeDataServiceException e) {
			e.printStackTrace();
			writeLog(e);
		}
		if(isVirtualForm && dataSource!=null){
			rs.executeSqlWithDataSource(sql,dataSource);
		}else{
			rs.executeSql(sql);
		}
		return rs.getCounts();
	}

	public String getAllModeDataList(int modeId, int pageNo, int pageSize,int recordCount, int userId, String conditions,String right,String isReturnDetail) {
		int languageid = 7;
		String returnxml = "";
		try {
			Document doc = new Document();
			Element root = new Element("ROOT");
			doc.setRootElement(root);
			//<header>
			Element headerElement = getHeaderElement(modeId, 0, userId);
			root.addContent(headerElement);
			//</header>
			//<search>
			root.addContent(getSearchElements(conditions,right));
			//</search>

			Element resultElement ;
			Element fieldElement;
			Element maintableElement ;
			Element detailElement;

			RecordSet rs = new RecordSet();
			FieldInfo fieldinfo = new FieldInfo();
			fieldinfo.getManTableField(modeId, languageid);
			fieldinfo.getDetailTableField(modeId, languageid);
			fieldinfo.getMainTableName(modeId);
			fieldinfo.getDetailTableNameList(modeId);

			List label_list = fieldinfo.getLabel_list();
			List type_list = fieldinfo.getType_list();
			List name_list = fieldinfo.getName_list();
			List value_list = fieldinfo.getValue_list();
			List htmltype_list = fieldinfo.getHtmltype_list();
			List dbtype_list = fieldinfo.getFielddbtype_list();
			List fieldid_list = fieldinfo.getFieldid_list();

			String tablename = fieldinfo.getTablename();
			int formId = getFormIdByModeId(modeId);
			boolean isVirtualForm = VirtualFormHandler.isVirtualForm(formId);
			String dataSource = "";
			String pkfieldname = "id";
			String fields = " id,modedatacreater,modedatacreatedate,modedatacreatetime ";
			if(isVirtualForm){
				FormInfoDao formInfoDao = new FormInfoDao();
				Map<String, Object> formInfo = formInfoDao.getFormInfoById(formId);
				dataSource = getVDataSource(formInfo);
				pkfieldname = Util.null2String(formInfo.get("vprimarykey"));
				tablename = VirtualFormHandler.getRealFromName(tablename);
				fields = "";
			}

			if (pageNo < 1){
				pageNo = 1;
			}
			String select = " select ";

			for(int i=0;i<name_list.size();i++){
				fields+=",";
				fields+=name_list.get(i).toString();
			}
			fields = fields.trim();
			if(fields.startsWith(",")){
				fields = fields.substring(1);
			}

			if(recordCount <=0 ){
				recordCount = getAllModeDataCount(modeId, userId, conditions,right);
			}

			String from = " from "+tablename+" ";

			String where = " where 1=1 ";

			if("y".equalsIgnoreCase(right.trim()) && !isVirtualForm){
				from +="t1,"+getShareSql(modeId, userId)+" t2 ";
				where += " and t1.id = t2.sourceid ";
			}

			if(!"".equals(conditions.trim())){
				conditions = " and "+conditions;
			}
			where += conditions;
			String orderby = " order by "+pkfieldname;
			String orderby1 = " order by "+pkfieldname +" desc";
			String orderby2 = " order by "+pkfieldname +" asc";

			String lable = "";
			String type = "";
			String name = "";
			String value = "";
			String htmltype = "";
			String dbtype = "";
			String fieldid = "";
			String id = "";
			String modedatacreater="";
			String modedatacreatedate="";
			String modedatacreatetime="";

			String sql = getPaginationSql(select, fields, from, where, orderby, orderby1, orderby2, pageNo, pageSize, recordCount,dataSource);
			//System.out.println(sql);
			writeLog(sql);
			rs.isReturnDecryptData(true);
			if(isVirtualForm && dataSource!=null){
				rs.executeSqlWithDataSource(sql,dataSource);
			}else {
				rs.executeSql(sql);
			}
			while(rs.next()){
				id = Util.null2String(rs.getString("id"));
				modedatacreater = Util.null2String(rs.getString("modedatacreater"));
				modedatacreatedate = Util.null2String(rs.getString("modedatacreatedate"));
				modedatacreatetime = Util.null2String(rs.getString("modedatacreatetime"));
				//<rows>
				resultElement = new Element("data");
				resultElement.setAttribute("id", id);

				resultElement.addContent(getHandlersElemens(modedatacreater ,modedatacreatedate ,modedatacreatetime));

				//<maintable>
				maintableElement = new Element("maintable");
				for (int i = 0; i < name_list.size(); i++) {
					name = name_list.get(i).toString();
					lable = label_list.get(i).toString();
					type = type_list.get(i).toString();
					htmltype = htmltype_list.get(i).toString();
					dbtype = dbtype_list.get(i).toString();
					fieldid = fieldid_list.get(i).toString();
					value = Util.null2String(rs.getString(tablename,name));
					//writeLog("lable:"+lable+"-type:"+type+"-htmltype:"+htmltype+"-dbtype:"+dbtype);
					try{
						fieldElement = getFieldElements(fieldid,lable, name,value,type,htmltype,dbtype);
						maintableElement.addContent(fieldElement);
					} catch (Exception e) {
						writeLog("fieldElement:"+e);
					}
				}
				resultElement.addContent(maintableElement);
				//</maintable>

				if(isReturnDetail.equalsIgnoreCase("y")){
					detailElement = getDetailDataElements(modeId,Integer.parseInt(id),languageid,fieldinfo);
					resultElement.addContent(detailElement);
				}

				root.addContent(resultElement);
				//<rows>
			}
			returnxml = createXml(doc);
		} catch (Exception e) {
			e.printStackTrace();
			writeLog("getAllModeDataList:"+e);
			returnxml = getErrorMsg(e.getMessage());
		}
		return returnxml;
	}

	public String getModeDataByID(int modeId, int Id, int userid,String right,String isReturnDetail) {
		int languageid = 7;
		String returnxml = "";
		try {
			RecordSet rs = new RecordSet();

			Document doc = new Document();
			Element root = new Element("ROOT");
			doc.setRootElement(root);
			//<header>
			Element headerElement = getHeaderElement(modeId, Id, userid);
			root.addContent(headerElement);
			//</header>

			//<search>
			root.addContent(getSearchElements("",right));
			//</search>

			Element fieldElement ;
			Element detailElement;
			Element maintableElement ;
			Element resultElement;

			FieldInfo fieldinfo = new FieldInfo();
			fieldinfo.getManTableField(modeId, languageid);
			fieldinfo.getDetailTableField(modeId, languageid);
			fieldinfo.getMainTableName(modeId);
			fieldinfo.getDetailTableNameList(modeId);

			List label_list = fieldinfo.getLabel_list();
			List type_list = fieldinfo.getType_list();
			List name_list = fieldinfo.getName_list();
			List value_list = fieldinfo.getValue_list();
			List htmltype_list = fieldinfo.getHtmltype_list();
			List dbtype_list = fieldinfo.getFielddbtype_list();
			List fieldid_list = fieldinfo.getFieldid_list();
			String tablename = fieldinfo.getTablename();
			int formId = getFormIdByModeId(modeId);

			//校验权限
			if("Y".equalsIgnoreCase(right)) {
				Map<String, Object> paramMap = new HashMap<>();
				paramMap.put("billid", Id);
				paramMap.put("type", 0);
				paramMap.put("modeId", modeId);
				paramMap.put("formId", formId);
				User user = new User(userid);
				CubeCheckCardRight cubeCheckCardRight = new CubeCheckCardRight(paramMap, user);
				Map<String, Object> rightInfo = cubeCheckCardRight.execute(null);
				String hasRight = Util.null2String(rightInfo.get("hasRight"));
				if (hasRight.contentEquals("false")) {
					returnxml = getReturnElements(Id, -1, "权限校验失败，无权限查看该数据");
					return returnxml;
				}
			}
			//权限校验结束

			boolean isVirtualForm = VirtualFormHandler.isVirtualForm(formId);
			String pkfieldname = "id";
			String dataSource = "";
			if (isVirtualForm){
				FormInfoDao formInfoDao = new FormInfoDao();
				Map<String, Object> formInfo = formInfoDao.getFormInfoById(formId);
				dataSource = getVDataSource(formInfo);
				pkfieldname = Util.null2String(formInfo.get("vprimarykey"));
				tablename = VirtualFormHandler.getRealFromName(tablename);
			}

			String sql = "";
			String lable = "";
			String type = "";
			String name = "";
			String value = "";
			String htmltype = "";
			String dbtype = "";
			String fieldid = "";
			String id = "";
			String modedatacreater="";
			String modedatacreatedate="";
			String modedatacreatetime="";
			rs.isReturnDecryptData(true);
			sql = "select * from "+tablename+" where "+pkfieldname+" = ?";
			if(isVirtualForm && dataSource!=null){
				rs.executeQueryWithDatasource(sql,dataSource,Id);
			}else{
				rs.executeQuery(sql,Id);
			}
			writeLog(sql);
			while(rs.next()){
				id = Util.null2String(rs.getString("id"));
				modedatacreater = Util.null2String(rs.getString("modedatacreater"));
				modedatacreatedate = Util.null2String(rs.getString("modedatacreatedate"));
				modedatacreatetime = Util.null2String(rs.getString("modedatacreatetime"));

				//<data>
				resultElement = new Element("data");
				resultElement.setAttribute("id", id);

				resultElement.addContent(getHandlersElemens(modedatacreater ,modedatacreatedate ,modedatacreatetime));

				maintableElement = new Element("maintable");

				for (int i = 0; i < name_list.size(); i++) {
					name = name_list.get(i).toString();
					lable = label_list.get(i).toString();
					type = type_list.get(i).toString();
					htmltype = htmltype_list.get(i).toString();
					dbtype = dbtype_list.get(i).toString();
					fieldid = fieldid_list.get(i).toString();
					value = Util.null2String(rs.getString(tablename,name));

					//fieldElement = getFieldElements(fieldid,lable, name,value,type,htmltype,dbtype);
					//maintableElement.addContent(fieldElement);

					//writeLog("lable:"+lable+"-type:"+type+"-htmltype:"+htmltype+"-dbtype:"+dbtype);

					try{
						fieldElement = getFieldElements(fieldid,lable, name,value,type,htmltype,dbtype);
						maintableElement.addContent(fieldElement);
					} catch (Exception e) {
						writeLog("1fieldElement:"+e);
					}
				}

				resultElement.addContent(maintableElement);

				if(isReturnDetail.equalsIgnoreCase("y")){
					detailElement = getDetailDataElements(modeId,Id,languageid,fieldinfo);
					resultElement.addContent(detailElement);
				}
				//</data>
				root.addContent(resultElement);
			}

			returnxml = createXml(doc);
			//System.out.println(returnxml);
		} catch (Exception e) {
			e.printStackTrace();
			writeLog("getModeDataByID:"+e);
			returnxml = getErrorMsg(e.getMessage());
		}
		return returnxml;
	}

	/**
	 * 解析files标签，并存入数据库
	 * <files>
     *   <filedname>xgwd</filedname>
     *   <filedlabel>相关文档</filedlabel>
     *   <file>
     *      <filename>11.html</filename>
     *      <filecontent>/weaver/weaver.file.FileDownload?fileid=18&amp;download=1</filecontent>
     *      <filecontenttype>application/octet-stream</filecontenttype>
     *   </file>
     *   <fieldshowname>3</fieldshowname>
     * </files>
	 * @param modeid
	 * @param userid
	 * @param billid
	 * @param tablename
	 * @param files_List
	 */
	private void resolveFilesElement(int modeid,int userid,int billid,String tablename,List<Element> files_List) throws Exception{
		if(null != files_List){
			for (int j = 0; j < files_List.size(); j++) { //循环files
				Element filesElement = files_List.get(j);

				String filedname = filesElement.getChildText("filedname");
				List<Element> file_List = filesElement.getChildren("file");
				String filename = "";
				String filecontent = "";
				String filecontenttype = "";
				String sql = "";
				String docids = "";
				RecordSet rs = new RecordSet();
				for (int i = 0; i < file_List.size(); i++) {
					filename = file_List.get(i).getChildText("filename");
					filecontent = file_List.get(i).getChildText("filecontent");
					filecontenttype = file_List.get(i).getChildText("filecontenttype");
					if(!"".equals(filename) && !"".equals(filecontent) ){
						if(!docids.equals("")){
							docids+=",";
						}
						int retDocID = fileutil.buildFile(modeid,userid, filecontent, filename);
						if(retDocID == 0){
                            throw new ModeDataServiceException(ModeDataExceptionEnum.URLGET_DOCID_ZERO.toString());
                        }
						docids += retDocID;
					}
				}
				sql = "update "+tablename+" set "+filedname+"='"+docids+"' where id=?";
				rs.executeUpdate(sql,billid);
				writeLog(sql);
			}
		}
	}

	/**
	 * 字段加密方法
	 * @param filedvalue
	 * @param tablename
	 * @param formid
	 * @param fieldname
	 */
	private String isFirldNeedEncrypt(String filedvalue,String tablename, int formid, String fieldname) throws Exception{
		boolean isVirtualForm = VirtualFormHandler.isVirtualForm(formid);
		if(isVirtualForm){
			tablename = VirtualFormHandler.getRealFromName(tablename);
		}
		RecordSet rs1 = new RecordSet();
		String sql="select t2.id,t2.fieldhtmltype,t2.fielddbtype,t2.type,t1.isencrypt from ModeFormFieldEncrypt t1 , workflow_billfield t2 where t1.fieldid=t2.id and t2.billid= '"
				+ formid + "' and t2.fieldname = '"+fieldname+"'";
		rs1.executeQuery(sql);
		if(rs1.next()){
			String fieldidtemp=Util.null2String(rs1.getString("id"));
			String fieldhtmltype=Util.null2String(rs1.getString("fieldhtmltype"));
			String type=Util.null2String(rs1.getString("type"));
			if("1".equals(fieldhtmltype)&& "1".equals(type)) {
				String isencrypt = new ModeFormFieldEncryptComInfo().getIsencrypt(fieldidtemp);
				if ("1".equals(isencrypt)) {
					filedvalue=CubeCipherUitl.encrypt(filedvalue);
				}
			}else if("3".equals(fieldhtmltype)&&("161".equals(type)||"162".equals(type))){
				String fielddbtype = Util.null2String(rs1.getString("fielddbtype"));
				filedvalue=CubeCipherUitl.getBrowserEncryptValue(fielddbtype, filedvalue,type);
			}
		}
		return filedvalue;
	}

	/**
	 * 保存权限、日志
	 * @param formmodeid
	 * @param billid
	 * @param userid
	 * @param right    save/deleteAll(保存/删除权限数据)
	 * @param operatetype 操作的类型： 1：新建 2：修改 3：删除 4：查看 5:调用webservice接口删除 6：调用webservice接口保存
	 */
	private void saveModeDataOthers(int formmodeid,int billid,int userid,String right,String operatetype) throws Exception{

		if("save".equals(right)){
			ModeRightInfo rightinfo = new ModeRightInfo();
			rightinfo.rebuildModeDataShareByEdit(userid,formmodeid,billid);//新建的时候添加共享
		}else if("deleteAll".equals(right)){
			RecordSet rs = new RecordSet();
			rs.executeUpdate("delete from modeDataShare_"+formmodeid+" where sourceid=?",billid);
		}

		//数据保存成功，执行接口
		//if(savestatus&&!src.equals("del")){
		//	ModeDataManager.doInterface(pageexpandid);
		//}

		//保存操作日志
		String clientaddress = "127.0.0.1";
		String operatedesc = SystemEnv.getHtmlLabelName(502911,weaver.general.Util.threadVarLanguage());//调用webservice接口
		int operateuserid = userid;
		int relatedid = billid;
		String relatedname = "";
		int htmllabelindex = 0;//#887673
		if("5".equals(operatetype)){
			operatedesc = operatedesc+SystemEnv.getHtmlLabelName(91,weaver.general.Util.threadVarLanguage());//调用webservice接口删除
			htmllabelindex = 91;
		}else if("6".equals(operatetype)){
			operatedesc = operatedesc+SystemEnv.getHtmlLabelName(86,weaver.general.Util.threadVarLanguage());//调用webservice接口保存
			htmllabelindex = 86;
		}else{
			operatedesc = SystemEnv.getHtmlLabelName(103,weaver.general.Util.threadVarLanguage());//修改
			htmllabelindex = 103;
		}
		ModeViewLog log = new ModeViewLog();
		log.resetParameter();
		log.setClientaddress(clientaddress);
		log.setModeid(formmodeid);
		log.setOperatedesc(operatedesc);
		log.setHtmllabelindex(htmllabelindex);
		log.setOperatetype(operatetype);
		log.setOperateuserid(operateuserid);
		log.setRelatedid(relatedid);
		log.setRelatedname(relatedname);
		if(deljsonString.length()>0){
			log.setDeldata(deljsonString);
		}
		long s = log.setSysLogInfo();
	}

	/**
	 * 获取数据共享权限 sql
	 * @param formmodeid
	 * @param userid
	 * @return
	 */
	public String getShareSql(int formmodeid,int userid){
		RecordSet rs = new RecordSet();
		User user = new User();
		String sql = "";
		if(userid==1){
			sql = "select * from HrmResourceManager where id="+userid;
		}else{
			sql="select * from HrmResource where id="+userid;
		}
		rs.executeSql(sql);
        rs.next();
		user.setUid(rs.getInt("id"));
        user.setLoginid(rs.getString("loginid"));
        user.setSeclevel(rs.getString("seclevel"));
        user.setUserDepartment(Util.getIntValue(rs.getString("departmentid"), 0));
        user.setUserSubCompany1(Util.getIntValue(rs.getString("subcompanyid1"), 0));
        user.setUserSubCompany2(Util.getIntValue(rs.getString("subcompanyid2"), 0));
        user.setUserSubCompany3(Util.getIntValue(rs.getString("subcompanyid3"), 0));
        user.setUserSubCompany4(Util.getIntValue(rs.getString("subcompanyid4"), 0));
        user.setManagerid(rs.getString("managerid"));
        user.setLogintype("1");

        ModeShareManager modeshare = new ModeShareManager();
        modeshare.setModeId(formmodeid);
        String rightsql = modeshare.getShareDetailTableByUser("formmode",user);
        return rightsql;
	}

	/**
	 * 获取header
	 * @param modeId
	 * @param Id
	 * @param userid
	 * @return
	 */
	private Element getHeaderElement(int modeId, int Id, int userid) {
		Element headerElement = new Element("header");
		Element element;

		element = new Element("userid");
		element.addContent(userid+"");
		headerElement.addContent(element);

		element = new Element("modeid");
		element.addContent(modeId+"");
		headerElement.addContent(element);

		String newid = "";
		if(Id>0){
			newid=Id+"";
		}
		element = new Element("id");
		element.addContent(newid);
		headerElement.addContent(element);
		return headerElement;
	}

	/**
	 * 获取searchElement
	 * @param condition
	 * @param right
	 * @return
	 */
	private Element getSearchElements(String condition,String right) {
		Element searchElement = new Element("search");
		Element element;

		element = new Element("condition");
		element.addContent(condition);
		searchElement.addContent(element);

		if("".equals(right.trim())) {
			right = "n";
		}

		element = new Element("right");
		element.addContent(right);
		searchElement.addContent(element);

		return searchElement;
	}

	private Element getHandlersElemens(String modedatacreater , String modedatacreatedate , String modedatacreatetime){
		Element handlersElement = new Element("handlers");
		Element element;

		element = new Element("modedatacreater");
		element.addContent(modedatacreater);
		handlersElement.addContent(element);

		element = new Element("modedatacreatershow");
		element.addContent(fieldInfo.getResourceName(modedatacreater));
		handlersElement.addContent(element);

		element = new Element("modedatacreatedate");
		element.addContent(modedatacreatedate);
		handlersElement.addContent(element);

		element = new Element("modedatacreatetime");
		element.addContent(modedatacreatetime);
		handlersElement.addContent(element);

		return handlersElement;
	}

	/**
	 * 获取明细表Element
	 * @param modeId
	 * @param Id
	 * @param languageid
	 * @param fieldinfo
	 * @return
	 * @throws Exception
	 */
	private Element getDetailDataElements(int modeId,int Id,int languageid,FieldInfo fieldinfo) throws Exception{
		RecordSet rs2 = new RecordSet();
		rs2.isReturnDecryptData(true);
		List dtlabel_list = fieldinfo.getDtlabel_list();
		List dttype_list = fieldinfo.getDttype_list();
		List dtname_list = fieldinfo.getDtname_list();
		List dtvalue_list = fieldinfo.getDtvalue_list();
		List dttablename_list = fieldinfo.getDttablename_list();
		List dthtmltype_list = fieldinfo.getDthtmltype_list();
		List dtdbtype_list = fieldinfo.getDtfielddbtype_list();
		List dtdfieldid_list = fieldinfo.getDtfieldid_list();
		String tablename = fieldinfo.getTablename();
		List detailtable_list = fieldinfo.getDetailtable_list();

		Element element;
		Element fieldElement;
		Element detailElement;
		Element detailtableElement;
		Element rowElement;

		String sql = "";
		String dtlable = "";
		String dttype = "";
		String dtname = "";
		String dtvalue = "";
		String dthtmltype="";
		String dtdbtype = "";
		String dtdfieldid = "";
		String detailtable = "";
		String id = "";

		//<detail>
		detailElement = new Element("detail");

		for (int i = 0; i < detailtable_list.size(); i++) {
			//<detailtable>
			detailtableElement  = new Element("detailtable");
			detailtableElement.setAttribute("id", i+"");

			detailtable = detailtable_list.get(i).toString();
			sql = "select d.* from "+tablename+" m,"+detailtable+" d"+" where m.id=d.mainid and m.id = "+Id;
			writeLog(sql);
			rs2.executeSql(sql);
			while(rs2.next()){
				id = Util.null2String(rs2.getString("id"));

				//<row>
				rowElement = new Element("row");
				rowElement.setAttribute("id", id);
				for (int j = 0; j < dtname_list.size(); j++) {
					if(detailtable.equals(dttablename_list.get(j).toString())){
						dtname = dtname_list.get(j).toString();
						dtlable = dtlabel_list.get(j).toString();
						dttype = dttype_list.get(j).toString();
						dthtmltype = dthtmltype_list.get(j).toString();
						dtdbtype = dtdbtype_list.get(j).toString();
						dtdfieldid = dtdfieldid_list.get(j).toString();
						dtvalue = Util.null2String(rs2.getString(detailtable,dtname));
						dtvalue = EncryptConfigBiz.getDecryptData(dtvalue);
						//<field>
						//writeLog("dtlable:"+dtlable+"-dttype:"+dttype+"-dthtmltype:"+dthtmltype+"-dtdbtype:"+dtdbtype);
						try{
							fieldElement = getFieldElements(dtdfieldid,dtlable, dtname,dtvalue,dttype,dthtmltype,dtdbtype);
							rowElement.addContent(fieldElement);
						} catch (Exception e) {
							writeLog("dtfieldElement:"+e);
						}
						//</field>
					}
				}
				detailtableElement.addContent(rowElement);
				//</row>
			}
			//<detailtable>
			detailElement.addContent(detailtableElement);
			//</detailtable>
		}
		//</detail>
		return detailElement;
	}

	/**
	 * 取得FieldElement
	 * @param id
	 * @param lable
	 * @param name
	 * @param value
	 * @param type
	 * @param htmltype
	 * @return
	 */
	private Element getFieldElements(String id,String lable, String name,
			String value,String type,String htmltype,String dbtype) {
		//System.out.println(value+"***"+htmltype+"***"+dbtype+"***"+lable);
		Element element;
		Element fieldElement;
		Element filesElement;
		Element fileElement;
		//if("6".equals(htmltype.trim()) && "1".equals(type.trim())){
		value = CubeCipherUitl.decrypt(value);
		if("6".equals(htmltype.trim())){
			//<files>
			filesElement = new Element("files");

			element = new Element("filedname");
			element.addContent(name);
			filesElement.addContent(element);
			element = new Element("filedlabel");
			element.addContent(lable);
			filesElement.addContent(element);
			element = new Element("fileddbtype");
			element.addContent(dbtype);
			filesElement.addContent(element);
			element = new Element("filedvalue");
			element.addContent(value);
			filesElement.addContent(element);
			if(!"".equals(value.trim())){
				RecordSet rs2 = new RecordSet();

				String sql = "";
				sql = "update docdetail set docPublishType='2' where id in ("+value+")"; //设置 外网 可以访问
				rs2.executeSql(sql);
				writeLog("getFieldElements:"+sql);
				sql = "select t2.imagefileid,t1.imagefilename,t1.imagefiletype,t1.filerealpath from ImageFile t1,docimagefile t2 where t1.imagefileid=t2.imagefileid and t2.docid in ("+value+")";
				//System.out.println(sql);
				rs2.executeSql(sql);
				while(rs2.next()){
					//文件节点begin
					fileElement = new Element("file");
					element = new Element("filename");
					element.addContent(rs2.getString("imagefilename"));
					fileElement.addContent(element);
					element = new Element("filecontent");
					element.addContent(oaip+"/weaver/weaver.file.FileDownload?fileid="+rs2.getString("imagefileid"));
					fileElement.addContent(element);
					element = new Element("filecontenttype");
					element.addContent("http");
					fileElement.addContent(element);
					filesElement.addContent(fileElement);
					//文件节点end
				}
			}else{
				//文件节点begin
				fileElement = new Element("file");
				element = new Element("filename");
				fileElement.addContent(element);
				element = new Element("filecontent");
				fileElement.addContent(element);
				element = new Element("filecontenttype");
				fileElement.addContent(element);
				filesElement.addContent(fileElement);
				//文件节点end
			}

			element = new Element("fieldshowname");
			element.addContent(value);
			filesElement.addContent(element);
			//</files>
			return filesElement;
		}else{
			String showname = "";
			if ("5".equals(htmltype.trim())) {//选择框
				if ("1".equals(type.trim())) {
					showname = getSelectItem(id.trim(), value);
//				} else if ("2".equals(type.trim())) {
				} else {
					String[] newvalue = value.split(",");
					for (String s : newvalue) {
						showname += getSelectItem(id.trim(), s) + ",";
					}
					showname = showname.substring(0, showname.length() - 1);
				}
			}else if("1".equals(htmltype.trim())||"2".equals(htmltype.trim())||"4".equals(htmltype.trim())){ //单行文本框、多行文本框、Check框
				showname = value;
			}else{
				showname = fieldInfo.getFieldName(value,Integer.parseInt(type),dbtype);
			}

			if("".equals(showname.trim())) {
				showname = value;
			}
			showname = EncryptConfigBiz.getDecryptData(showname);
			//System.out.println(name+"***"+lable);
			//<field>
			fieldElement = new Element("field");
			element = new Element("filedname");
			element.addContent(name);
			fieldElement.addContent(element);
			element = new Element("filedlabel");
			element.addContent(lable.trim());
			fieldElement.addContent(element);
			element = new Element("fileddbtype");
			element.addContent(dbtype);
			fieldElement.addContent(element);
			element = new Element("filedvalue");
			element.addContent(value);
			fieldElement.addContent(element);
			element = new Element("fieldshowname");
			element.addContent(showname);
			fieldElement.addContent(element);
			//</field>
		}
		return fieldElement;
	}
	/**
	 * 通过字段ID、下拉框id 获取下拉框显示名
	 * @param fieldid
	 * @param value
	 * @return
	 */
	private String getSelectItem(String fieldid,String value){
		String item = "";
		if(!value.equals("")){
			RecordSet rs = new RecordSet();
			rs.executeSql("select selectname, selectvalue,isdefault,cancel from workflow_SelectItem where fieldid="+fieldid+" and selectvalue="+value);
	        while(rs.next()){
	            item=Util.toHtmlMode(rs.getString("selectname"));
	        }
		}
		return item;
	}

	private String getErrorMsg(String errorMsg){
		Document doc = new Document();
		Element root = new Element("ROOT");
		Element returnEle = new Element("return");
		doc.setRootElement(root);

		Element element = new Element("errormsg");
		element.addContent(errorMsg);
		returnEle.addContent(element);

		root.addContent(returnEle);
		return createXml(doc);
	}

	/**
	 *
	 * @param id
	 * @param code
	 * @param message
	 * @return
	 *
	 * <?xml version="1.0" encoding="UTF-8"?>
	 * <ROOT>
     *   <return>
     *     <id>1<id>
     *     <returnnode>0</returnnode>
     *     <returnmessage>操作成功！</returnmessage>
   	 *     </return>
     * </ROOT>
	 */
	private String getReturnElements(Integer id,int code,String message){
		Document doc = new Document();
		Element root = new Element("ROOT");
		Element returnEle = new Element("return");
		Element element ;
		doc.setRootElement(root);

		element = new Element("id");
		element.addContent(id+"");
		returnEle.addContent(element);

		element = new Element("returnnode");
		element.addContent(code+"");
		returnEle.addContent(element);

		element = new Element("returnmessage");
		element.addContent(new CDATA(message));
		returnEle.addContent(element);

		root.addContent(returnEle);

		return createXml(doc);
	}

	/**
	 * 取得分页的SQL
	 * @param select sql中select
	 * @param fields sql中fields
	 * @param from sql中from
	 * @param where sql中where
	 * @param orderby sql中orderby
	 * @param orderby1 sql中orderby1
	 * @param orderby2 sql中orderby2
	 * @param pageNo 当前页数
	 * @param pageSize 每页记录数
	 * @param recordCount 记录总数
	 * @return String 分页SQL
	 */
	private String getPaginationSql(String select, String fields, String from, String where, String orderby, String orderby1, String orderby2, int pageNo, int pageSize, int recordCount,String datasource) {
		String sql = "";
		RecordSet rs = new RecordSet();
		String dbtype = "";
		if(!"".equals(datasource)){
			dbtype = rs.getDBTypeByPoolName(datasource);
		}else{
			dbtype = rs.getDBType();
		}
		if ("oracle".equals(dbtype)) {
			int firstResult = pageNo * pageSize + 1;
			int endResult = (pageNo - 1) * pageSize;
			sql = " select * from ( select my_table.*,rownum as my_rownum from ( select tableA.*,rownum as r from ( " + select + " " + fields + " " + from + " " + where + " " + orderby + " ) tableA  ) my_table where rownum < " + firstResult + " ) where my_rownum > " + endResult;
		} else if("mysql".equals(dbtype)){
			int beginResult = (pageNo - 1) * pageSize;
			sql = select  + " " + fields + " " + from + " " + where + " " + orderby + " limit "+beginResult+","+pageSize;
		}
		else if("postgresql".equals(dbtype)){
			int beginResult = (pageNo - 1) * pageSize;
			sql = select  + " " + fields + " " + from + " " + where + " " + orderby + " limit "+pageSize+" offset "+ beginResult;
		}
		else {
			int firstResult = pageSize * pageNo;
			int endResult = pageSize;
			if (firstResult > recordCount) {
				firstResult = recordCount;
				endResult = recordCount - (pageSize * (pageNo - 1));
			}
			if (pageNo == 1){
				sql = select + " top " + endResult + " " + fields + " " + from + " " + where + " " + orderby;
			}else{
				sql = " select top " + endResult + " * from ( select top " + endResult + " * from ( " + select + " top " + firstResult + " " + fields + " " + from + " " + where + " " + orderby + " " + ") tbltemp1 " + orderby1 + " ) tbltemp2 " + orderby2;
			}
		}
		return sql;
	}

	private String getCurrentDate(){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
		return df.format(new Date());
	}

	private String getCurrentTime(){
		SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
		return df.format(new Date());
	}

	/**
	 * 将document转换成xml字符串
	 * @param doc
	 * @return
	 */
	public String createXml(Document doc){
		XMLOutputter outputter = null;
		Format format = Format.getCompactFormat();
		format.setEncoding("UTF-8");
		format.setIndent(null);
		outputter = new XMLOutputter(format);
		return outputter.outputString(doc);
	}
	/**
	 * 通过表单id得到外部数据源
	 * @param formInfo
	 * @return
	 */
	public String getVDataSource(Map<String, Object> formInfo) throws ModeDataServiceException {
		String pointid = Util.null2String(formInfo.get("vdatasource"));
		String virtualformtype = Util.null2String(formInfo.get("virtualformtype"));
		if("1".equals(virtualformtype)){
			throw new ModeDataServiceException(ModeDataExceptionEnum.NOT_SUPPORT_View_VIRFORM.toString());
		}
		if("$ECOLOGY_SYS_LOCAL_POOLNAME".equals(pointid)){
			pointid=null;//null表示使用的是本地数据库
		}
		return pointid;
	}
	/**
	 * 通过模块id得到formid
	 * @param modeId
	 * @return
	 */
	public int getFormIdByModeId(int modeId){
		RecordSet rs = new RecordSet();
		int formId = 0;
		String sql = "select formid from modeinfo where id=?";
		rs.executeQuery(sql,modeId);
		if(rs.next()){
			formId = rs.getInt("formid");
		}
		return formId;
	}

	private String removePrefixAndSuffix(String content,String fix){
		content = Util.null2String(content).trim();
		if(content.endsWith(fix)){
			content = content.substring(0,content.length()-1);
		}
		if(content.startsWith(fix)){
			content = content.substring(1);
		}
		return content;
	}

	/**
	 * 将查询的结果集转化为MAP
	 * @param rs
	 * @return
	 */
	public Map<String,String> recordSet2Map(RecordSet rs){
		Map<String,String> valueMap=new HashMap<String,String>();
		String [] columNames=rs.getColumnName();
		if(columNames==null) return valueMap;
		for(String columName:columNames){
			valueMap.put(columName.toLowerCase(), rs.getString(columName));
		}
		return valueMap;
	}

	public void doInterface(String billid,String formid,String modeid,int userid, int pageexpandid,Map<String, Object> params){
		ModeDataInterface modeDataInterface = new ModeDataInterface();
		modeDataInterface.setBillid(billid);
		modeDataInterface.setFormid(Util.getIntValue(formid));
		modeDataInterface.setPageexpandid(pageexpandid);
		modeDataInterface.setModeid(Util.getIntValue(modeid));
		modeDataInterface.setUser(new User(userid));
		modeDataInterface.setParams(params);
		Map<String, String> execute = modeDataInterface.execute();
		//this.pageExpendResult=JSONObject.toJSONString(execute);
	}
}
